const cateBox = document.querySelector('.category')
const box = document.querySelector('.container')
const filterBox = document.querySelector('.filter')
const saleTypeBox = document.querySelector('.saleType')
const sortBox = document.querySelector('.sort')
const select = document.querySelector('select')
const inp = document.querySelector('.searchBox > input')
const pageInfoBox = document.querySelector('.pageInfo')
const contentBox = document.querySelector('.content')
// const mulu=document.querySelector(".nav>.mulu")
// const list2=document.querySelector(".nav>.list2")
// mulu.onmouseover=function(){
//   list2.classList.add("active")
// }
// list2.onmouseover=function(){
//   list2.classList.add("active")
// }
// mulu.onmouseleave=function(){
//   list2.classList.remove("active")
// }
// list2.onmouseleave=function(){
//   list2.classList.remove("active")
// }
getCategoryList()
async function getCategoryList() {
  const res = await pAjax({
    url: 'http://localhost:8888/goods/category',
    dataType: 'json'
  })
  let str = '<li class="cate active">全部</li>'
  res.list.forEach(item => {
    str += `<li class="cate">${ item }</li>`
  })
  cateBox.innerHTML = str
}


const info = {
  current: 1,
  pagesize: 12,
  search: '',
  filter: '',
  saleType: 10,
  sortType: 'id',
  sortMethod: 'ASC',
  category: ''
}

let total = 10
box.addEventListener('click', e => {
  e = e || window.event
  const target = e.target || e.srcElement
  if (target.className === 'cate') {
    for (var i = 0; i < cateBox.children.length; i++) {
      cateBox.children[i].classList.remove('active')
    }
    target.classList.add('active')
    info.category = target.innerText === '全部' ? '' : target.innerText
    info.current = 1
    getGoodsList()
  }

  if (target.className === 'f') {
    for (var i = 0; i < filterBox.children.length; i++) {
      filterBox.children[i].classList.remove('active')
    }
    target.classList.add('active')
    info.filter = target.dataset.filter ? target.dataset.filter : ''
    info.current = 1
    getGoodsList()
  }

  if (target.className === 's') {
    for (var i = 0; i < saleTypeBox.children.length; i++) {
      saleTypeBox.children[i].classList.remove('active')
    }
    target.classList.add('active')
    info.saleType = target.innerText === '全部' ? 10 : target.innerText
    info.current = 1
    getGoodsList()
  }
  if (target.className === 'sort2') {
    for (var i = 0; i < sortBox.children.length; i++) {
      sortBox.children[i].classList.remove('active')
    }
    target.classList.add('active')
    info.sortType = target.dataset.type ? target.dataset.type : 'id'
    info.sortMethod = target.dataset.method ? target.dataset.method : 'ASC'
    getGoodsList()
  }

  if (target.className === 'prev') {
    if (info.current <= 1) return
    info.current--
    getGoodsList()
  }

  if (target.className === 'next') {
    if(info.current >= total) return
    info.current++
    getGoodsList()
  }
})
select.addEventListener('change', () => {
  info.pagesize = select.value
  info.current = 1
  getGoodsList()
})

inp.addEventListener('input', () => {
  info.search = inp.value.trim()
  info.current = 1
  getGoodsList()
})

getGoodsList()
async function getGoodsList() {
  const data = querystringify(info)
  const res = await pAjax({
    url: 'http://localhost:8888/goods/list',
    data: data,
    dataType: 'json'
  })
  total = res.total
  pageInfoBox.innerText = `${ info.current } / ${ total }`
  let str = ''

  res.list.forEach(item => {
    str += `
      <li>
        <div class="show">
          <img data-id="${ item.goods_id }" src="${ item.img_big_logo }" alt="">
          <span class="hot ${ item.is_hot ? 'active' : '' }"> HOT </span>
          <span class="sale ${ item.is_sale ? 'active' : '' }"> SALE </span>
        </div>
        <div class="info">
          <p class="title">${ item.title }</p>
          <p>
            折扣: ${ item.sale_type }
          </p>
          <p class="price">
            <del class="old"> ￥ ${ item.price } </del>
            <span class="current"> ￥ ${ item.current_price } </span>
          </p>
          <p>
            <button data-id="${ item.goods_id }">加入购物车</button>
          </p>
        </div>
      </li>
    `
  })

  contentBox.innerHTML = str
}

contentBox.addEventListener('click', async e => {
  e = e || window.event
  const target = e.target || e.srcElement
  if (target.nodeName === 'IMG') {
    const id = target.dataset.id
    window.sessionStorage.setItem('id', id)
    window.location.href = './detail.html'
  }
  if (target.nodeName === 'BUTTON') {
    const login = window.localStorage.getItem('login')
    if (!login) {
      window.localStorage.setItem('url', 'list')
      window.location.href = './login.html'
      return
    }
    const id = window.localStorage.getItem('id')
    const goods_id = target.dataset.id
    const token = window.localStorage.getItem('token')
    const res = await pAjax({
      url: 'http://localhost:8888/cart/add',
      method: 'POST',
      data: `id=${ id }&goodsId=${ goods_id }`,
      dataType: 'json',
      token: token
    })

    if (res.code !== 1) {
      window.localStorage.setItem('url', 'list')
      window.location.href = './login.html'
      return
    }
    alert('加入购物车成功')
  }
})

const denglu=document.querySelector(".nav>.denglu")
 const cart=document.querySelector(".nav>.cart")
 cart.addEventListener('click',()=>window.open("../views/cart.html"))
 denglu.addEventListener('click',()=>window.open("../views/login.html"))

 const onBox = document.querySelector('.on')
 const offBox = document.querySelector('.off')
 const nameBox = document.querySelector('.username')
 const selfBtn = document.querySelector('.self')
 const id = window.localStorage.getItem('id')

testLogin()
function testLogin() {
  const login = window.localStorage.getItem('login')
  if (login !== '1') {
    offBox.classList.add('active')
    onBox.classList.remove('active')
    return
  }

  const token = window.localStorage.getItem('token')
  const xhr = new XMLHttpRequest()
  xhr.open('GET', 'http://localhost:8888/users/info?id=' + id)
  xhr.onload = () => testHandler(xhr)
  xhr.setRequestHeader('authorization', token)
  xhr.send()
}
function testHandler(xhr) {
  const res = JSON.parse(xhr.responseText)
  console.log(res)
  if (res.code !== 1) {
    offBox.classList.add('active')
    onBox.classList.remove('active')
    denglu.classList.remove('active')
    return
  }
  nameBox.innerText = res.info.nickname
  onBox.classList.add('active')
  offBox.classList.remove('active')
  denglu.classList.add('active')

}

const logoutBtn = document.querySelector('.logout')
logoutBtn.addEventListener('click', () => {
  ajax({
    url: 'http://localhost:8888/users/logout',
    data: `id=${ id }`,
    dataType: 'json',
    success: function (res) {
      if (res.code === 1) window.location.reload()
    }
  })
})


  

   
  
  
